#!/bin/bash
if [ $# != 2 ]; then
    echo 'usage: regex_str.sh {file} "{regex}"'
    exit 1
fi

declare -A lineCountMap #出现的次数
declare -A charTotalCountMap #总的字符数
declare -A charMinMap #最小的字符数
declare -A charMaxMap #最大的字符数

AddStrToMap() {
    match=$1
    line=$2

    lineCount=${lineCountMap["$match"]}
    charTotalCount=${charTotalCountMap["$match"]}
    charMin=${charMinMap["$match"]}
    charMax=${charMaxMap["$match"]}
    if [ -z "$lineCount" ]; then
        lineCount=0
        charTotalCount=0
        charMin=9999999999
        charMax=0
    fi
    lineCountMap["$match"]=`expr $lineCount + 1`
    charCount=`echo -n $line | wc -c`
    charTotalCountMap["$match"]=`expr $charTotalCount + $charCount`
    if [ $charCount -lt $charMin ]; then
        charMin=$charCount
    fi
    if [ $charCount -gt $charMax ]; then
        charMax=$charCount
    fi
    charMinMap["$match"]=$charMin
    charMaxMap["$match"]=$charMax
}

while read line; do
    match=`echo -n $line | egrep -o "$2"` 
    if [ -z "$match" ]; then
        continue
    fi
    AddStrToMap "$match" "$line"
done < $1

echo "lineCountMap: ${lineCountMap[@]}"
echo "charTMap: ${!charTotalCountMap[@]}"
echo "charMinMap: ${!charMinMap[@]}"
echo "charMaxMap:${!charMaxMap[@]}"

echo -e 'Match\tLine\tTotal\tMin\tMax\tAvg'
for match in ${!lineCountMap[@]};do
    echo "$match|1"
    lineCount=${lineCountMap[$match]}
    charCount=${charTotalCountMap[$match]}
    charMin=${charMinMap[$match]}
    charMax=${charMaxMap[$match]}
    if [ -z "$lineCount" ]; then
        charAverage=""
    else
        charAverage=`expr $charCount / $lineCount`
    fi
    echo -e "$match\t$lineCount\t$charCount\t$charMin\t$charMax\t$charAverage"
done
